public class Solution695 {
    /**
     *给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。
     * 你可以假设二维矩阵的四个边缘都被水包围着。
     *
     * 找到给定的二维数组中**最大的岛屿面积**。(如果没有岛屿，则返回面积为0。)
     *
     */

    public int maxAreaOfIsland(int[][] grid) {
        int rows = grid.length;
        if (rows == 0) {
            return 0;
        }
        int cols = grid[0].length;
        int max = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (grid[row][col] != 1) {
                    continue;
                }
                max = Math.max(max, buildIsland(grid, rows, cols, row, col));
            }
        }
        return max;
    }

    public int buildIsland(int[][] grid, int rows, int cols, int row, int col) {
        if (row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] == 0) {
            return 0;
        }
        grid[row][col] = 0;
        return 1 +
                buildIsland(grid, rows, cols, row - 1, col) +
                buildIsland(grid, rows, cols, row + 1, col) +
                buildIsland(grid, rows, cols, row, col - 1) +
                buildIsland(grid, rows, cols, row, col + 1);
    }
}
